package com.qf.blog.email.job;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.blog.core.dto.EmailDto;
import com.qf.blog.core.utils.EmailUtils;
import com.qf.blog.email.entity.EmailErrorEntity;
import com.qf.blog.email.mapper.EmailErrorMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class SendErrorEmailJob {

    @Autowired
    private EmailErrorMapper emailErrorMapper;

    @Scheduled(cron = "0/10 * * * * *")
    public void reSendEmail() {
        log.debug("定时任务开始发送邮件");

        // 1.获取发送失败的邮件
        List<EmailErrorEntity> errorEmails = getErroeEmails();

        // 2.遍历重新发送邮件
        for (EmailErrorEntity errorEmail : errorEmails) {
            String emailText = errorEmail.getEmailText();
            try {
//                int status = EmailUtils.sendEmailInfoUser(JSON.parseObject(emailText, EmailDto.class));
//                if (status > 1) {
                    // 重新发送成功，修改MySQL中邮件的状态
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

    private List<EmailErrorEntity> getErroeEmails() {
        QueryWrapper<EmailErrorEntity> wrapper = new QueryWrapper();
        wrapper.eq("status", 1);
        return emailErrorMapper.selectList(wrapper);
    }
}
